import React, { useEffect, useState, useRef } from 'react';
import { StatItem } from '../types';
import ReactECharts from 'echarts-for-react';
import service from '../utils/axios';
import { useSprings, animated } from '@react-spring/web';
import EChartsWrapper from '../components/EChartsWrapper';

const defaultStats: StatItem[] = [
  { title: '今日订单数', value: 124, trend: '+12%', trendUp: true },
  { title: '本月销售额', value: '¥45,280', trend: '+8%', trendUp: true },
  { title: '活跃用户', value: 1245, trend: '+5%', trendUp: true },
  { title: '转化率', value: '24.8%', trend: '+2.5%', trendUp: true }
];

function parseNumber(val: string | number) {
  if (typeof val === 'number') return val;
  if (typeof val === 'string') {
    const num = parseFloat(val.replace(/[^\d.]/g, ''));
    return isNaN(num) ? 0 : num;
  }
  return 0;
}

const Overview: React.FC = () => {

  // Stats for the dashboard
  const [stats, setStats] = useState<StatItem[]>(defaultStats);
  const [loading, setLoading] = useState(true);
  const firstLoad = useRef(true);
  // 数字动画
  const [springs, api] = useSprings(stats.length, i => ({ val: parseNumber(stats[i]?.value) }));
  const [monthlySales, setMonthlySales] = useState<MonthlySale[]>([]);
  const [userGrowth, setUserGrowth] = useState<UserGrowth[]>([]);
  const [productCategories, setProductCategories] = useState<ProductCategory[]>([]);
  const [pageLoading, setPageLoading] = useState(true);

  // 页面加载完成后关闭全屏 loading
  useEffect(() => {
    if (!loading && monthlySales.length && userGrowth.length && productCategories.length) {
      setPageLoading(false);
    }
  }, [loading, monthlySales, userGrowth, productCategories]);

  // 只用 WebSocket 实时更新 stats
  useEffect(() => {
    setLoading(true);
    let ws: WebSocket | null = null;
    try {
      ws = new window.WebSocket('ws://localhost:3000');
      ws.onopen = () => { setLoading(false); };
      ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.stats) setStats(data.stats);
        if (data.monitor) setMonitor(data.monitor);
        if (data.twins) setTwins(data.twins);
        if (data.warehouse) setWarehouse(data.warehouse);
        if (data.logistics) setLogistics(data.logistics);
      };
      ws.onerror = () => { };
      ws.onclose = () => { };
    } catch {
      // setNetworkError(true); // Original code had this line commented out
      // setHasTriedConnect(true); // Original code had this line commented out
    }
    return () => { if (ws) ws.close(); };
  }, []);

  // 监听 stats 变化，启动数字动画
  useEffect(() => {
    api.start(i => ({ val: parseNumber(stats[i]?.value), config: { tension: 120, friction: 20 } }));
  }, []);

  // 删除前端 mock 数据，改为接口数据
  interface MonthlySale { month: string; value: number; }
  interface UserGrowth { month: string; newUsers: number; activeUsers: number; }
  interface ProductCategory { name: string; percentage: number; }

  // 用户增长率缓存逻辑
  useEffect(() => {
    // 先尝试从 localStorage 读取
    const cache = localStorage.getItem('userGrowth');
    if (cache) {
      try {
        const parsed = JSON.parse(cache);
        if (Array.isArray(parsed)) setUserGrowth(parsed);
      } catch {}
    }
    // 异步拉取最新数据
    service.get('/LXL/overview/user-growth').then((res: any) => {
      if (Array.isArray(res)) {
        setUserGrowth(res);
        localStorage.setItem('userGrowth', JSON.stringify(res));
      }
    }).catch((err: any) => {
      if (err.code === 'ECONNABORTED') {
        // setNetworkError(true); // Original code had this line commented out
      }
    });
  }, []);

  // 其它接口请求
  useEffect(() => {
    service.get('/LXL/overview/sales').then((res: any) => {
      if (Array.isArray(res)) setMonthlySales(res);
    }).catch((err: any) => {
      if (err.code === 'ECONNABORTED') {
        // setNetworkError(true); // Original code had this line commented out
      }
    });
    service.get('/LXL/overview/categories').then((res: any) => {
      if (Array.isArray(res)) setProductCategories(res);
    }).catch((err: any) => {
      if (err.code === 'ECONNABORTED') {
        // setNetworkError(true); // Original code had this line commented out
      }
    });
  }, []);

  // 图表option统一加黑色字体
  const salesOption = {
    title: { text: '销售趋势', left: 'center', textStyle: { color: '#222' } },
    xAxis: { type: 'category', data: monthlySales.map(i => i.month), axisLabel: { color: '#222' } },
    yAxis: { type: 'value', axisLabel: { color: '#222' } },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}: {c}'
    },
    series: [
      {
        data: monthlySales.map(i => i.value),
        type: 'bar',
        itemStyle: { color: '#1890ff' }
        // 无emphasis.label
      }
    ]
  };

  const userGrowthOption = {
    title: { text: '用户增长', left: 'center', textStyle: { color: '#222' } },
    xAxis: { type: 'category', data: userGrowth.map(i => i.month), axisLabel: { color: '#222' } },
    yAxis: { type: 'value', axisLabel: { color: '#222' } },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any[]) => {
        // params为数组
        return params.map((p: any) => `${p.seriesName}: ${p.value}`).join('<br/>');
      }
    },
    series: [
      {
        name: '新增用户',
        data: userGrowth.map(i => i.newUsers),
        type: 'line',
        itemStyle: { color: '#52c41a' },
        smooth: true
        // 无emphasis.label
      },
      {
        name: '活跃用户',
        data: userGrowth.map(i => i.activeUsers),
        type: 'line',
        itemStyle: { color: '#faad14' },
        smooth: true
        // 无emphasis.label
      }
    ]
  };

  const pieColors = [
    '#1890ff', '#faad14', '#52c41a', '#eb2f96', '#13c2c2', '#722ed1', '#f5222d', '#fa541c', '#2f54eb', '#a0d911', '#fa8c16', '#b37feb', '#36cfc9', '#ffec3d', '#d3adf7', '#ff85c0'
  ];
  const categoryPieOption = {
    title: {
      text: '商品类别分布',
      left: 'center',
      top: 10,
      textStyle: { color: '#222', fontSize: 20, fontWeight: 'bold' }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%' // b=名称，c=值
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '55%'],
        avoidLabelOverlap: false,
        label: { show: false },
        labelLine: { show: false },
        data: productCategories.map((category, idx) => ({
          value: category.percentage,
          name: category.name,
          itemStyle: {
            color: pieColors[idx % pieColors.length]
          }
        }))
      }
    ]
  };

  // 实时监控区数据
  const [monitor, setMonitor] = useState({
    onlineUsers: 0,
    processingOrders: 0,
    avgResponse: '0.0s',
    availability: '100.0%'
  });

  // 订单流转孪生数据
  const [twins, setTwins] = useState<{id:string, name:string, count:number, color:string}[]>([]);

  // 仓库/物流孪生数据
  const [warehouse, setWarehouse] = useState<{areas:any[], robots:any[]}>({areas:[], robots:[]});
  const [logistics, setLogistics] = useState<any[]>([]);

  // 只用 WebSocket 实时更新 stats、monitor、twins、warehouse、logistics
  useEffect(() => {
    setLoading(true);
    const ws = new window.WebSocket('ws://localhost:3000');
    ws.onopen = () => setLoading(false);
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.stats) setStats(data.stats);
      if (data.monitor) setMonitor(data.monitor);
      if (data.twins) setTwins(data.twins);
      if (data.warehouse) setWarehouse(data.warehouse);
      if (data.logistics) setLogistics(data.logistics);
    };
    return () => ws.close();
  }, []);

  return (
    <div className="bigscreen-container" style={{ padding: 32, background: '#fff', minHeight: '150vh',minWidth:"1200px", position: 'relative' }}>
      {pageLoading && (
        <div style={{
          position: 'fixed',
          left: 0,
          top: 0,
          width: '100vw',
          height: '100vh',
          background: 'rgba(255,255,255,0.85)',
          zIndex: 9999,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 28,
          fontWeight: 700,
          color: '#1890ff',
          letterSpacing: 2
        }}>
          <span className="loading-spinner" style={{ marginRight: 16, display: 'inline-block', width: 32, height: 32, border: '4px solid #91d5ff', borderTop: '4px solid #1890ff', borderRadius: '50%', animation: 'spin 1s linear infinite', verticalAlign: 'middle' }} />
          正在加载数据...
          <style>{`@keyframes spin { 100% { transform: rotate(360deg); } }`}</style>
        </div>
      )}
      <div className="stats-row" style={{ display: 'flex', gap: 24, marginBottom: 32 }}>
        {/* 统计卡片 */}
        {loading ? (
          <div>加载中...</div>
        ) : (
          stats.map((stat, index) => (
            <div
              key={index}
              className="card"
              style={{
                flex: 1,
                background: '#f8f9fa',
                border: '2px solid #e0e0e0',
                borderRadius: 16,
                boxShadow: '0 4px 24px rgba(0,0,0,0.06)',
                padding: 24,
                margin: 0,
                minWidth: 180,
                textAlign: 'center',
                color: '#333',
                position: 'relative',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s',
              }}
            >
              <h3 style={{ fontSize: 20, fontWeight: 600, marginBottom: 12, letterSpacing: 1 }}>{stat.title}</h3>
              <div className="stat" style={{ fontSize: 36, fontWeight: 700, marginBottom: 8 }}>
                {typeof stat.value === 'string' && stat.value.startsWith('¥') ? (
                  <>
                    ¥<animated.span>
                      {springs[index].val.to(val => Math.round(val).toLocaleString())}
                    </animated.span>
                  </>
                ) : typeof stat.value === 'string' && stat.value.endsWith('%') ? (
                  <>
                    <animated.span>
                      {springs[index].val.to(val => val.toFixed(1))}
                    </animated.span>%
                  </>
                ) : (
                  <animated.span>
                    {springs[index].val.to(val => Math.round(val).toLocaleString())}
                  </animated.span>
                )}
              </div>
              {stat.trend && (
                <div className={`trend ${stat.trendUp ? 'trend-up' : stat.trendUp === false ? 'trend-down' : 'trend-neutral'}`}
                  style={{ fontSize: 16, color: stat.trendUp ? '#52c41a' : stat.trendUp === false ? '#ff4d4f' : '#aaa' }}>
                  {stat.trend} {stat.trendUp ? '↑' : stat.trendUp === false ? '↓' : ''}
                </div>
              )}
            </div>
          ))
        )}
      </div>
      <div
        className="charts-row"
        style={{
          display: 'flex',
          gap: 24,
          marginBottom: 32,
          alignItems: 'stretch', // 让三张卡片高度一致
          minWidth: 900,
        }}
      >
        <div
          style={{
            flex: 2,
            background: '#f8f9fa',
            border: '2px solid #e0e0e0',
            borderRadius: 16,
            boxShadow: '0 4px 24px rgba(0,0,0,0.06)',
            padding: 24,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            minHeight: 360,
          }}
        >
          <EChartsWrapper option={salesOption} loading={loading} height={320} />
        </div>
        <div
          style={{
            flex: 2,
            background: '#f8f9fa',
            border: '2px solid #e0e0e0',
            borderRadius: 16,
            boxShadow: '0 4px 24px rgba(0,0,0,0.06)',
            padding: 24,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            minHeight: 360,
          }}
        >
          <EChartsWrapper option={userGrowthOption} loading={loading} height={320} />
        </div>
        <div
          style={{
            flex: 1,
            background: '#f8f9fa',
            border: '2px solid #e0e0e0',
            borderRadius: 16,
            boxShadow: '0 4px 24px rgba(0,0,0,0.06)',
            padding: 24,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            minHeight: 360,
          }}
        >
          <EChartsWrapper option={categoryPieOption} loading={loading} height={200} width={180} />
          <div style={{ width: '100%', marginTop: 16 }}>
            {productCategories.map((cat, idx) => (
              <div key={cat.name} style={{ display: 'flex', alignItems: 'center', marginBottom: 6, fontSize: 15 }}>
                <span style={{
                  display: 'inline-block',
                  width: 12,
                  height: 12,
                  borderRadius: '50%',
                  background: pieColors[idx % pieColors.length],
                  marginRight: 8
                }} />
                <span style={{ flex: 1 }}>{cat.name}</span>
                <span style={{ fontWeight: 600 }}>{cat.percentage}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="realtime-row" style={{
        marginTop: 24,
        background: '#f8f9fa',
        border: '2px solid #e0e0e0',
        borderRadius: 16,
        boxShadow: '0 4px 24px rgba(0,0,0,0.06)',
        padding: 24,
        color: '#333'
      }}>
        {/* 实时监控组件 */}
        <div style={{ display: 'flex', gap: 48, justifyContent: 'center', alignItems: 'center' }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, fontWeight: 700 }}>{monitor.onlineUsers}</div>
            <div style={{ fontSize: 16, color: '#888' }}>当前在线用户</div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, fontWeight: 700 }}>{monitor.processingOrders}</div>
            <div style={{ fontSize: 16, color: '#888' }}>进行中的订单</div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, fontWeight: 700 }}>{monitor.avgResponse}</div>
            <div style={{ fontSize: 16, color: '#888' }}>平均响应时间</div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, fontWeight: 700 }}>{monitor.availability}</div>
            <div style={{ fontSize: 16, color: '#888' }}>系统可用性</div>
          </div>
        </div>
      </div>
      {/* 订单流转孪生可视化区域 */}
      <div style={{
        background: 'linear-gradient(135deg, #f0f2f5 60%, #e6f7ff 100%)',
        borderRadius: 16,
        margin: '32px 0',
        padding: 24,
        boxShadow: '0 4px 24px rgba(24,144,255,0.08)',
        minWidth: 600,
        maxWidth: 900,
        maxHeight:500,
        marginLeft: 'auto',
        marginRight: 'auto',
        border: '1.5px solid #bae7ff',
      }}>
        <h3 style={{ textAlign: 'center', marginBottom: 16, fontSize: 22, fontWeight: 700, color: '#1890ff', letterSpacing: 2 }}>订单流转实时孪生</h3>
        {twins.length === 0 ? (
          <div style={{textAlign:'center',color:'#aaa',padding:40}}>加载中...</div>
        ) : (
          <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'flex-end', height: 260 }}>
            {twins.map(twin => (
              <div key={twin.id} style={{ textAlign: 'center', flex: 1 }}>
                <div style={{
                  width: 38,
                  height: Math.max(24, twin.count * 2.2),
                  background: `linear-gradient(180deg, ${twin.color} 60%, #fff 100%)`,
                  borderRadius: 12,
                  margin: '0 auto',
                  boxShadow: '0 2px 12px rgba(24,144,255,0.10)',
                  position: 'relative',
                  transition: 'height 0.5s',
                  display: 'flex',
                  alignItems: 'flex-end',
                  justifyContent: 'center',
                }}>
                  <span style={{
                    position: 'absolute',
                    top: -28,
                    left: '50%',
                    transform: 'translateX(-50%)',
                    fontSize: 20,
                    fontWeight: 700,
                    color: twin.color,
                    textShadow: '0 2px 8px #fff',
                  }}>{twin.count}</span>
                </div>
                <div style={{ fontSize: 15, marginTop: 10, color: '#333', fontWeight: 500 }}>{twin.name}</div>
              </div>
            ))}
          </div>
        )}
      </div>
      {/* 仓库布局孪生可视化区域 */}
      <div style={{ background: '#fffbe6', borderRadius: 16, margin: '32px 0', padding: 16, boxShadow: '0 2px 8px #faad14', minWidth: 400, maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
        <h3 style={{ textAlign: 'center', marginBottom: 8, color: '#faad14' }}>仓库布局孪生</h3>
        <svg width={300} height={220} style={{ background: '#fff', border: '1px solid #eee' }}>
          {/* 区域 */}
          {warehouse.areas.map(area => (
            <g key={area.id}>
              <rect x={area.x} y={area.y} width={80} height={50} fill="#ffe58f" stroke="#faad14" strokeWidth={2} rx={8} />
              <text x={area.x + 40} y={area.y + 25} textAnchor="middle" fontSize={16} fill="#faad14">{area.name}</text>
              <text x={area.x + 40} y={area.y + 45} textAnchor="middle" fontSize={12} fill="#333">库存:{area.stock}</text>
            </g>
          ))}
          {/* 机器人 */}
          {warehouse.robots.map(robot => (
            <g key={robot.id}>
              <circle cx={robot.x} cy={robot.y} r={12} fill={robot.status === '作业' ? '#52c41a' : '#1890ff'} />
              <text x={robot.x} y={robot.y + 24} textAnchor="middle" fontSize={12} fill="#333">{robot.name}</text>
            </g>
          ))}
        </svg>
      </div>
      {/* 物流配送孪生可视化区域 */}
      <div style={{ background: '#e6f7ff', borderRadius: 16, margin: '32px 0', padding: 16, boxShadow: '0 2px 8px #1890ff', minWidth: 400, maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
        <h3 style={{ textAlign: 'center', marginBottom: 8, color: '#1890ff' }}>物流配送孪生</h3>
        <svg width={300} height={160} style={{ background: '#fff', border: '1px solid #eee' }}>
          {/* 路线 */}
          {logistics.filter(l => l.route).map(l => (
            <polyline key={l.id + '-route'} points={l.route.map((p:any) => p.join(',')).join(' ')} fill="none" stroke="#1890ff" strokeWidth={2} />
          ))}
          {/* 车辆/包裹 */}
          {logistics.map(l => (
            <g key={l.id}>
              <rect x={l.x-10} y={l.y-10} width={20} height={20} fill={l.type === '货车' ? '#1890ff' : '#faad14'} rx={5} />
              <text x={l.x} y={l.y + 24} textAnchor="middle" fontSize={12} fill="#333">{l.type}</text>
            </g>
          ))}
        </svg>
      </div>
    </div>
  );
};

export default Overview; 